﻿#include "stdafx.h"
#include "fuzzySearch.h"
#include "table.h"

#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QSqlRecord>
#include <QCompleter>
#include <QDebug>

FuzzySearch::FuzzySearch(QWidget *parent) :
    QWidget(parent)
{
    _model = new QSqlTableModel;
    _view = new QTableView;
    _view->setModel(_model);
 
    _model->setTable("video");
    _model->setEditStrategy(QSqlTableModel::OnFieldChange);
 
    connect(_model, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
            this, SLOT(slotModelDataChanged(QModelIndex,QModelIndex)));
 
    _model->select();
 
    QVBoxLayout* vBox = new QVBoxLayout(this); 
    QHBoxLayout* hBox = new QHBoxLayout;
    vBox->addLayout(hBox);
	vBox->addWidget(_view);
 
	hBox->addWidget(_filter = new QComboBox, 1);
	hBox->addWidget(_search = new QPushButton("Search"));
	hBox->addWidget(_setting = new QPushButton("Setting"));
 
	connect(_filter, SIGNAL(currentIndexChanged(QString)),
		this, SLOT(slotFilterChanged(QString)));

	_filter->setEditable(true);
	_filter->setDuplicatesEnabled(false);
	_filter->installEventFilter(this);
	connect(_search, &QPushButton::clicked, [&]() 
	{
		slotFilterChanged(_filter->currentText());
	});

	{
		Table table;
		auto list = table.GetTexts();
		_filter->addItems(list);

		for (auto& item : list)
		{
			_set.insert(item);
		}
	}

	connect(_setting, &QPushButton::clicked, [&]()
	{
		saveFilters();

		Table table;
		table.setModal(true);
		int result = table.exec();
		if (result == QDialog::Accepted)
		{
			auto list = table.GetTexts();
			_filter->clear();
			_filter->addItems(list);

			_set.clear();
			for (auto& item : list)
			{
				_set.insert(item);
			}
		}
	});
 
    slotModelDataChanged(QModelIndex(), QModelIndex());
}
 
FuzzySearch::~FuzzySearch()
{
	saveFilters();
}

bool FuzzySearch::eventFilter(QObject * obj, QEvent *event)
{
	if (obj == _filter)
	{
		if (event->type() == QEvent::KeyPress)
		{
			QKeyEvent *ke = static_cast<QKeyEvent*>(event);
			if (ke->key() == Qt::Key_Enter || ke->key() == Qt::Key_Return)
			{
				slotFilterChanged(_filter->currentText());
				return true;
			}
		}

		return false;
	}

	return QWidget::eventFilter(obj, event);
}

void FuzzySearch::slotFilterChanged(QString filter)
{
    if(filter.isEmpty())
    {
        _model->setFilter("");
        _model->select();
        return;
    }

    //  username like filter or password like  filter .......
    QSqlRecord record = _model->record();
    QString modelFilter;
    for(int i=0; i<record.count(); ++i)
    {
        if(i!=0)
        {
            modelFilter += " or ";
        }
        QString field = record.fieldName(i);
        QString subFilter = QString().sprintf("%s like '%%%s%%'", field.toUtf8().data(), filter.toUtf8().data()); 
        modelFilter += subFilter;
 
    }

    qDebug() << modelFilter;
    _model->setFilter(modelFilter);
    _model->select();

	if (!_set.contains(filter) && _model->rowCount() > 0)
	{
		_filter->addItem(filter);
		_set.insert(filter);
	}
}
 
void FuzzySearch::saveFilters()
{
	QSqlDatabase db = QSqlDatabase::database("video.db");
	QSqlQuery query(db);
	for (auto& item : _set)
	{
		query.exec(QString("insert into 'setting' values('%1')").arg(item));
	}
}

void FuzzySearch::slotModelDataChanged(QModelIndex,QModelIndex)
{
    QStringList strList;
    for(int i=0; i<_model->rowCount(); ++i)
    {
        QSqlRecord record = _model->record(i);
        for(int j=0; j<record.count(); ++j)
        {
            QVariant var = record.value(j);
            if(var.isNull()) continue;
            strList << var.toString();
        }
    }

    qDebug() << strList;
    QCompleter* completer = new QCompleter(strList);
    _filter->setCompleter(completer);
}
